/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fileUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 模仿的Unix grep命令
 * BufferedReader包装FileReader类
 * @author Administrator
 */
public class GrepReader extends BufferedReader {

    String pattern;

    public GrepReader(Reader in, String pattern) {
        super(in);
        this.pattern = pattern;
    }

    public final String readLine() throws IOException {
        String line;
        do {
            line = super.readLine();
        } while ((line != null) && line.indexOf(pattern) == -1);
        return line;
    }

    public static void main(String args[]) {
        try {
            GrepReader in = new GrepReader(new FileReader("GrepReader.java"), "GrepReader");
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }

    public static void grep(String regex,String file) throws FileNotFoundException, IOException {
        InputStream in = System.in;

        in = new BufferedInputStream(new FileInputStream(file));
        Pattern p = null;

        p = Pattern.compile(regex);

        BufferedReader buff = new BufferedReader(new InputStreamReader(in));

        String a;
        for (a = buff.readLine(); a != null; a = buff.readLine()) {
            Matcher m = p.matcher(a);
            if (m.find()) {
                System.out.println(a);
            }
        }
    }
}
